﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using _4chanManager.Logic;

namespace _4chanManager.Panels
{
    /// <summary>
    /// Interaction logic for GifConvertControl.xaml
    /// </summary>
    public partial class GifConvertControl : UserControl
    {
        private BackgroundWorker _bgw;
        private bool RemoveGifFlag = true;
        public GifConvertControl()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            _bgw = new BackgroundWorker {WorkerReportsProgress = true};
            _bgw.DoWork += bgw_DoWork;
        }

        private void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            GifConverter gc = new GifConverter(myPathPanel.Path) {RemoveGifAfterConvert = RemoveGifFlag};

            gc.AppendMessage += AppendMessage;
            gc.SubProgressChanged += gc_SubProgressChanged;
            gc.TaskCompleted += gc_TaskCompleted;
            gc.Start();
           
        }

        void gc_TaskCompleted()
        {
            AppendMessage("Task Completed");
            if (!btnStartStop.Dispatcher.CheckAccess())
                btnStartStop.Dispatcher.Invoke(() => btnStartStop.IsEnabled = true);
            else
                btnStartStop.IsEnabled = true;

            _bgw.ReportProgress(100);
        }


        private void gc_SubProgressChanged(int percent)
        {
            SubProgressBar.Dispatcher.InvokeAsync(() => SubProgressBar.Value = percent);
        }

        private void AppendMessage(string message)
        {
            txtActual.Dispatcher.InvokeAsync(() =>
            {
                txtActual.AppendText(message);
                txtActual.Text += Environment.NewLine;
                txtActual.ScrollToEnd();
            });
            if (message.Contains("Directory"))
            {
                txtAktualnyFolder.Dispatcher.InvokeAsync(() =>
                {
                    txtAktualnyFolder.Text = message.Replace("Directory: ", string.Empty);
                });
            }
        }

        private void btnStartStop_Click(object sender, RoutedEventArgs e)
        {
            btnStartStop.IsEnabled = false;
            _bgw.RunWorkerAsync();

        }

        private void chkRemoveGif_Click(object sender, RoutedEventArgs e)
        {
            if (chkRemoveGif.IsChecked != null) RemoveGifFlag = (bool)chkRemoveGif.IsChecked;
        }
    }
}
